package edu.whut.controller;

import edu.whut.entity.Author;
import edu.whut.entity.CommonResult;
import edu.whut.service.AuthorService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/auhtor")
public class AuthorController {

    @Resource
    AuthorService authorService;

    @RequestMapping("/add")
    public CommonResult<Author> addAuthor(@RequestBody Author author){
        if(authorService.addAuthor(author)){
            return new CommonResult<>(200,"success",null);
        }
        return new CommonResult<>(400,"error",null);
    }

    @RequestMapping("/delete")
    public CommonResult<Author> deleteAuthor(@RequestParam("authorId") Long authorId){
        if(authorService.deleteAuthor(authorId)){
            return new CommonResult<>(200,"success",null);
        }
        return new CommonResult<>(400,"error",null);
    }

    @RequestMapping("/update")
    public CommonResult<Author> updateAuthor(@RequestBody Author author){
        if(authorService.updateAuthor(author)){
            return new CommonResult<>(200,"success",null);
        }
        return new CommonResult<>(400,"error",null);
    }

    @RequestMapping("/getById")
    public CommonResult<Author> getAuthorById(@RequestParam("authorId") Long authorId){
        if(authorService.getAuthorById(authorId)!=null){
            return new CommonResult<>(200,"success",authorService.getAuthorById(authorId));
        }
        return new CommonResult<>(400,"error",null);
    }

    @RequestMapping("/getByName")
    public CommonResult<Author> getAuthorByName(@RequestParam("name") String name){
        if(authorService.getAuthorByName(name)!=null){
            return new CommonResult<>(200,"success",authorService.getAuthorByName(name));
        }
        return new CommonResult<>(400,"error",null);
    }

    /**
     * 功能：模糊查找作者
     * @param field
     * @return 作者
     */
    @RequestMapping("/fuzzySearch")
    public CommonResult<List<Author>> fuzzySearch(@RequestParam("field") String field){
        List<Author> authors = authorService.fuzzySearch(field);
        if(authors!=null){
            return new CommonResult<>(200,"success",authors);
        }
        return new CommonResult<>(400,"error",null);
    }
}
